<template>
  <!-- 项目录入 -->
  <el-dialog
    v-model="props.visible"
    width="800px"
    :show-close="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          {{ t('procurement.ProjectAdd.t0') }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>

    <div
      class="main"
      v-if="store.category !== null"
    >
      <el-form
        ref="formEl"
        :model="formData"
        :rules="rules"
        label-width="150px"
        status-icon
      >
        <!-- 采购中类 -->
        <el-form-item
          :label="t('procurement.ProjectAdd.l1')"
          prop="mediumId"
        >
          <el-radio-group
            v-model="formData.mediumId"
            @change="changeMedium"
          >
            <el-radio
              v-for="item in secondLevelOptions"
              :key="item.purchasingProjectId"
              :label="item.purchasingProjectId"
            >
              {{ item.projectName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 采购小类 （备件名称） -->
        <el-form-item
          v-if="threeLevelOptions.length"
          :label="t('procurement.ProjectAdd.l2_1')"
          prop="purchasingProjectId"
        >
          <el-radio-group v-model="formData.purchasingProjectId">
            <el-radio
              v-for="item in threeLevelOptions"
              :key="item.purchasingProjectId"
              :label="item.purchasingProjectId"
            >
              {{ item.projectName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 采购编号 备件编号IMPA NO. -->
        <el-form-item
          :label="t('procurement.ProjectAdd.l3_1')"
          prop="procureNo"
        >
          <el-input
            v-model.trim="formData.procureNo"
            :placeholder="t('procurement.ProjectAdd.p3_1')"
            :maxlength="50"
          />
        </el-form-item>
        <!-- 图纸号 -->
        <el-form-item
          :label="t('procurement.ProjectAdd.l11')"
          prop="drawingNumber"
        >
          <el-input
            v-model.trim="formData.drawingNumber"
            :placeholder="t('procurement.ProjectAdd.p11')"
            :maxlength="50"
          />
        </el-form-item>
        <el-form-item
          :label="t('procurement.ProjectAdd.l4')"
          prop="procureSpec"
        >
          <div class="grid">
            <el-input
              v-model.trim="formData.procureSpec"
              :placeholder="t('procurement.ProjectAdd.p4-1')"
              :maxlength="50"
            />
            <el-input
              v-model.trim="formData.procureModel"
              :placeholder="t('procurement.ProjectAdd.p4-2')"
              :maxlength="50"
            />
          </div>
        </el-form-item>
        <!-- 采购数量 -->
        <el-form-item
          :label="t('procurement.ProjectAdd.l10')"
          prop="requireCount"
        >
          <div class="grid">
            <el-input-number
              v-model="formData.requireCount"
              :placeholder="t('procurement.ProjectAdd.p10')"
              :controls="false"
              style="width: 100%"
              :max="999999999"
            />
            <el-input
              v-model.trim="formData.unit"
              :placeholder="t('procurement.ProjectAdd.p7-2')"
              :maxlength="50"
            />
          </div>
        </el-form-item>
        <!-- 采购项目备注 -->
        <el-form-item
          :label="t('procurement.ProjectAdd.l8')"
          prop="remark"
        >
          <el-input
            v-model.trim="formData.remark"
            type="textarea"
            :placeholder="t('procurement.ProjectAdd.p8')"
            :maxlength="100"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer flexcc">
        <el-button
          color="#252628"
          plain
          @click="cancel"
        >
          {{ t('cancelText') }}
        </el-button>
        <el-button
          v-if="!editRow"
          color="#252628"
          plain
          @click="confirm(true)"
        >
          <!-- 新增一个 -->
          {{ t('procurement.ProjectAdd.newAddOne') }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="confirm(false)"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useProcurement from '@/stores/procurement'
import { editOrderDetailApi } from '@/service/procurement'
import { cloneDeep } from 'lodash'

const { t, locale } = useI18n()

const router = useRouter()
const route = useRoute()

const store = useProcurement()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editRow: {
    type: Object,
    default: () => null
  },
  checkedRow: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['close', 'getDetail'])

// title
const dialogTitle = computed(() => {
  const obj = {
    设备: t('procurement.ProjectAdd.t1'),
    备件: t('procurement.ProjectAdd.t2'),
    油水: t('procurement.ProjectAdd.t3'),
    伙食: t('procurement.ProjectAdd.t4')
  }
  return obj[store.category.projectNameCn]
})

const handleClose = () => {
  emit('close')
}

const cancel = () => {
  handleClose()
}
const confirm = (isAddone = false) => {
  if (!formEl.value) return
  formEl.value.validate((valid, fields) => {
    if (valid) {
      const params = cloneDeep(formData.value)
      editOrderDetailApi(params).then(({ msg }) => {
        ElMessage.success(msg)

        if (isAddone) {
          formData.value = {
            ...formDataTmp,
            mediumId: params.mediumId,
            purchasingProjectId: params.purchasingProjectId
          }
        } else {
          handleClose()
        }

        emit('getDetail')
      })
    }
  })
}

// 二级类别
const secondLevelOptions = computed(() => {
  const res = store.categoryList.find((item) => item.purchasingProjectId === store.category.purchasingProjectId)?.purchasingProjectWebVoList
  if (res.length === 1) {
    formData.value.mediumId = res[0].purchasingProjectId
  }
  return res
})

// 三级类别
const threeLevelOptions = computed(() => {
  return secondLevelOptions.value.find((item) => item.purchasingProjectId === formData.value.mediumId)?.purchasingProjectWebVoList || []
})

// 选择二级时
const changeMedium = (val) => {
  if (threeLevelOptions.value.length) {
    if (formData.value.purchasingProjectId) {
      formData.value.purchasingProjectId = null
    }
  } else {
    formData.value.purchasingProjectId = val
  }
}

// 表单
const formEl = ref(null)
const formDataTmp = {
  largeId: store.category.purchasingProjectId, // 一级id
  procureOrderId: store.orderInfo.id // 采购单Id
}
const formData = ref(cloneDeep(formDataTmp))
if (props.editRow) {
  formData.value = { ...formData.value, ...props.editRow } // 回显
}
if (props.checkedRow) {
  formData.value.previousId = props.checkedRow.id // 上一级id
}
const validator = {
  procureSpec: (rule, value, callback) => {
    if (!value) {
      return callback(new Error(t('procurement.ProjectAdd.r4_1')))
    }
    if (!formData.value.procureModel) {
      return callback(new Error(t('procurement.ProjectAdd.r4_2')))
    }

    callback()
  },
  requireCount: (rule, value, callback) => {
    if (!value) {
      return callback(new Error(t('procurement.ProjectAdd.r7_1')))
    }
    if (!formData.value.unit && !['伙食'].includes(store.category.projectNameCn)) {
      return callback(new Error(t('procurement.ProjectAdd.r7_2')))
    }

    callback()
  }
}
const rules = reactive({
  mediumId: [{ required: true, message: t('procurement.ProjectAdd.r1'), trigger: 'change' }],
  purchasingProjectId: [{ required: true, message: t('procurement.ProjectAdd.r2_1'), trigger: 'change' }],
  procureNo: [{ required: false, message: t('procurement.ProjectAdd.r3_1'), trigger: 'change' }],
  procureSpec: [{ required: true, validator: validator.procureSpec, trigger: 'change' }],
  classificationSociety: [{ required: true, message: t('procurement.ProjectAdd.r5'), trigger: 'change' }],
  procureName: [{ required: true, message: t('procurement.ProjectAdd.r6'), trigger: 'change' }],
  requireCount: [{ required: true, validator: validator.requireCount, trigger: 'change' }],
  remark: [{ required: false, message: t('procurement.ProjectAdd.r8'), trigger: 'change' }],
  projectContent: [{ required: true, message: t('procurement.ProjectAdd.r9'), trigger: 'change' }]
})
</script>

<style scoped lang="scss">
.main {
  padding: 0 50px;
}
.grid {
  display: grid;
  width: 100%;
  grid-template-columns: repeat(2, 49%);
  justify-content: space-between;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
